<?php

class Model_Tdi extends RL_Model2
{
	private $sections_with_del;
	private $sections_without_del;

	public function getTdi($oid)
	{
		return $this->store->getObject($oid);
	}
	
	/*
	 * Удаляет раздел.
	 * 
	 * @param $oid
	 */
	public function delSection($oid) {
		$object = $this->getTdi( $oid );
		$object->is_deleted = 1;
		return $object->save();
	}
	
	public function createTdi($info) {
		$community_oid = $info['community_oid'];
		if (empty($community_oid)) return false;

		//$info['title'] = '';
		$info['color'] = isset($info['color']) ? $info['color'] : $this->getColorForType($info['itype']);
		//$info['itype'] = '';
		//$info['url'] = '';
		//$info['view'] = 'showfeed';
		$info['community_oid'] = $community_oid;
		$info['show_in_main_menu'] = isset($info['show_in_main_menu']) ? $info['show_in_main_menu'] : true;

		$tdi = $this->store->create('ftdi', $info);
		$tdi->save();

		$tdi->inSense("tdi");
		$tdi->save();
		
		return $tdi;
	}
	
	/**
	 * Изменить раздел.
	 *
	 * @param mixed $oid oid tdi
	 * @param array $info данные (для $obj->data)
	 *              {url, community_oid, title, itype, color, view}
	 * @access public
	 * @return ftdi
	*/
	public function changeTdi($oid, array $info)
	{
		$community_oid = $info['community_oid'];
		if (empty($community_oid)) return false;

		$ql = 'select objects where tdi.oid = :0';
		$tdi = $this->store->find( $ql, array($oid))->next();
		if (empty($tdi)) {
			// community not found
			return false;
		}
		// FIX : 2008-02-08 : lucky
		// по условию, itype не меняется => цвет не меняется тоже
		//
		//if (!isset($info['color']) && isset($info['itype'])) $info['color'] = $this->tdi_getColorForType($info['itype']);
		unset($info['itype'], $info['color']);

		foreach ($info as $k=>$v) {
			switch ($name) {
			default:
				$tdi->data[$k] = $v;
			}
		}
		$tdi->save();
		$tdi->updateSense("tdi");

		return $tdi;
	}
	
	public function getSections( array $tdi_oids, $include_deleted = true ) {
		
		if ( (!isset($this->sections_with_del)) || (!isset($this->sections_without_del)) ) {
			$sections_with_del = array();
			$sections_without_del = array();
			foreach ( $tdi_oids as $oid ) {
				$tdq['objects']['oid']['=='] = $oid;
				$rs = $this->store->find( $tdq );
				$tdi_instance = $rs->next();
				// для запроса к хранилищу
				
				// удобная структура для разных целей
				$sections_with_del[ $oid ] = $tdi_instance->data;
				$sections_with_del[ $oid ]['oid'] = $tdi_instance->id;
				$sections_with_del[ $oid ]['is_deleted'] = $tdi_instance->is_deleted;
				
				if ($tdi_instance->is_deleted==0) {
					$sections_without_del[ $oid ] = $tdi_instance->data;
					$sections_without_del[ $oid ]['oid'] = $tdi_instance->id;
					$sections_without_del[ $oid ]['is_deleted'] = $tdi_instance->is_deleted;
				}
			}
			$this->sections_with_del = $sections_with_del;
			$this->sections_without_del = $sections_without_del;
		}
		
		if ($include_deleted) {
			return $this->sections_with_del;
		} else {
			return $this->sections_without_del;
		}	
				
	}

	// для смены порядка разделов
	public function moveEnd ($oid, $community_oid)	{

		$table     = 'store_class_tdi_order';
		$fld_oid    = 'oid';
		$fld_order = 'order';
		$and_const = "community_oid = {$community_oid}";
		$db = $this->store->db;

		$e_fld_oid   = '`'.$fld_oid.'`';
		$e_fld_order = '`'.$fld_order.'`';

		// найдем строчку
		$sql = "SELECT {$e_fld_oid}, {$e_fld_order}"
			.     " FROM {$table}"
			.     " WHERE {$and_const} AND {$e_fld_oid} = {$oid}"
			;
		$me = $db->queryOne($sql);
		// найдем максимальное значение
		$sql = "SELECT MAX({$e_fld_order}) AS {$e_fld_order}"
			.     " FROM {$table}"
			.     " WHERE {$and_const}"
			.     " GROUP BY community_oid"
			;
		$max = $db->queryOne($sql);


		// поехали

		$sql = array();
		if (empty($me)) { // еще нет записи -- вставляем новую в конец
			$data = array(
				       $e_fld_oid => $oid,
				     $e_fld_order => ($max[$fld_order] ? $max[$fld_order] + 1 : 1),
				'community_oid' => $community_oid,
			);
			$fs = array(); $vs = array();
			foreach ($data as $f=>$v) {
				$fs[] = $f;
				$vs[] = $db->quote($v);
			}
			$fields = implode(', ', $fs);
			$values = implode(', ', $vs);
			$sql[] = "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
		} else { // уже есть. нужно поменять порядок
			if (false && $me[$fld_order] === $max[$fld_order]) { // мы и так в конце
			} else { // сдвигаем вверх все что ниже
				$sql[] = "UPDATE {$table}"
					.     " SET {$e_fld_order} = {$e_fld_order} - 1"
					.     " WHERE {$e_fld_order} >= ".$me[$fld_order]
					.        " AND ".$and_const
					;
				$sql[] = "UPDATE {$table}"
					.     " SET {$e_fld_order} = ".$max[$fld_order]
					.     " WHERE {$e_fld_oid} = ".$me[$fld_oid]
					.        " AND ".$and_const
					;
			}
		}
		foreach ($sql as $q) {
			if (!($status = $db->execute($q))) { break; }
		}
		return $status;
	} // end of function moveEnd
	
	public function setShowInMainMenuState($oid, $community_oid, $state=True /*true - show, false - hide*/)	{

		$ql = 'select objects where tdi.oid = :0 and tdi.community_oid = :1';
		$tdi = $this->store->find( $ql, array($oid, $community_oid))->next();
		if (empty($tdi)) {
			// community not found
			return false;
		}
		$tdi->data['show_in_main_menu'] = $state;

		$tdi->save();
		$tdi->updateSense("tdi");

		return $tdi;
	}
	
	public function moveUp($oid, $community_oid) {

		$table     = 'store_class_tdi_order';
		$fld_oid    = 'oid';
		$fld_order = 'order';
		$and_const = "community_oid = {$community_oid}";
		$db = $this->store->db;

		$e_fld_oid   = '`'.$fld_oid.'`';
		$e_fld_order = '`'.$fld_order.'`';

		// найдем строчку
		$sql = "SELECT {$e_fld_oid}, {$e_fld_order}"
			.     " FROM {$table}"
			.     " WHERE {$and_const} AND {$e_fld_oid} = {$oid}"
			;
		$me = $db->queryOne($sql);
		// найдем следующее значение
		$sql = "SELECT {$e_fld_oid}, {$e_fld_order}"
			.     " FROM {$table}"
			.     " WHERE {$and_const}"
			.        " AND {$e_fld_order} > ".$me[$fld_order]
			.     " ORDER BY {$e_fld_order}"
			.     " LIMIT 1"
			;
		$next = $db->queryOne($sql);
		$sql = array();
		if ($me && $next) { // уже есть. нужно поменять порядок
			// сдвигаем ввер все что
			$sql[] = "UPDATE {$table}"
				.     " SET {$e_fld_order} = ".$next[$fld_order]
				.     " WHERE {$e_fld_oid} = ".$me[$fld_oid]
				;
			$sql[] = "UPDATE {$table}"
				.     " SET {$e_fld_order} = ".$me[$fld_order]
				.     " WHERE {$e_fld_oid} = ".$next[$fld_oid]
				;
		}
		foreach ($sql as $q) {
			//var_dump($q);
			if (!($status = $db->execute($q))) { break; }
		}
		return $status;
	} // end of function moveUp
	
	// переместить раздел в конец
	public function moveDown($oid, $community_oid)	{

		$table     = 'store_class_tdi_order';
		$fld_oid    = 'oid';
		$fld_order = 'order';
		$and_const = "community_oid = {$community_oid}";
		$db = $this->store->db;

		$e_fld_oid   = '`'.$fld_oid.'`';
		$e_fld_order = '`'.$fld_order.'`';

		// найдем строчку
		$sql = "SELECT {$e_fld_oid}, {$e_fld_order}"
			.     " FROM {$table}"
			.     " WHERE {$and_const} AND {$e_fld_oid} = {$oid}"
			;
		$me = $db->queryOne($sql);
		// найдем предыдущее значение
		$sql = "SELECT {$e_fld_oid}, {$e_fld_order}"
			.     " FROM {$table}"
			.     " WHERE {$and_const}"
			.        " AND {$e_fld_order} < ".$me[$fld_order]
			.     " ORDER BY {$e_fld_order} DESC"
			.     " LIMIT 1"
			;
		$next = $db->queryOne($sql);
		$sql = array();
		if ($me && $next) { // уже есть. нужно поменять порядок
			// сдвигаем ввер все что
			$sql[] = "UPDATE {$table}"
				.     " SET {$e_fld_order} = ".$next[$fld_order]
				.     " WHERE {$e_fld_oid} = ".$me[$fld_oid]
				;
			$sql[] = "UPDATE {$table}"
				.     " SET {$e_fld_order} = ".$me[$fld_order]
				.     " WHERE {$e_fld_oid} = ".$next[$fld_oid]
				;
		}
		foreach ($sql as $q) {
			//var_dump($q);
			if (!($status = $db->execute($q))) { break; }
		}
		return $status;
	} // end of function moveDown

	// цвет для типа документа
	public static function getColorForType($tdi_type)
	{
		switch ($tdi_type) {
		case 'doc': $res = '01'; break;
		case 'link': $res = '02'; break;
		case 'image': $res = '03'; break;
		case 'file': $res = '04'; break;
		case 'issue': $res = '05'; break;
		case 'review': $res = '06'; break;
		default : $res = '01'; break;
		}
		return $res;
	} // end of function tdi_getColorForType


}
